!! Module to be used if particle present
module mod_read_write
  use technical
  use mod_2dflu
  implicit none
  save
  integer :: nfname=9
!
!
!--------------------------
namelist /basic_pars/ &
      lfluid,lforcing,lparticle,limmersed_boundary,nn,vis,vis2,delta,maxiter,tmax,nrun,pmax,&
      navg,nloop,kini,mu,kdrag,mu2,lcalc_Gradu,xx0,yy0,loutputpy,oamp,hydro_ini,&
      lwrite_velocity_output,lascii_output,lwrite_vel_rspace,lwrite_streamfunction,datadir
contains
!! ---------------SUBROUINES ---------------
!%--

!! Read basic data
subroutine read_basic(unit,iostat)
  integer, intent(in) :: unit
  integer, intent(inout), optional :: iostat
!----------
  if (present(iostat)) then
    read(unit,NML=basic_pars,IOSTAT=iostat)
  else
    read(unit,NML=basic_pars)
  endif
  rewind(unit)
endsubroutine read_basic
! ----------------------------------------
subroutine write_2dScalarField_ascii(psi,varname,n1,n2)
  integer, intent(in) :: n1,n2
  double precision, dimension(n1,n2), intent(in) :: psi
  integer :: i1,i2
  character(len=*) :: varname
  character(len=labellen) :: fname
!----------------------
  fname=trim(datadir)//trim(varname)//'.ascii'
  call reiterate_file(fname,nfname) 
  open(unit=5,file=fname,status='new')
   do i2=1,n2
     write(5,*) (psi(i1,i2),i1=1,n1)
   enddo
  close(5)
endsubroutine write_2dScalarField_ascii
!%-----------------------------------------------
subroutine write_2dScalarField_binary(psi,varname,n1,n2)
  integer, intent(in) :: n1,n2
  double precision, dimension(n1,n2), intent(in) :: psi
  integer :: i1,i2 
  character(len=*) :: varname
  character(len=labellen) :: fname
!----------------------
  fname=trim(datadir)//trim(varname)//'.binary'
  call reiterate_file(fname,nfname) 
  open(unit=5,file=fname,status='new',form='unformatted')
  write(5) ((psi(i1,i2),i1=1,n1),i2=1,n2)
  close(5)
endsubroutine write_2dScalarField_binary
!%-----------------------------------------------
subroutine reiterate_file(fname,nfname)
 integer, intent(in) :: nfname
 character(len=labellen), intent(inout) :: fname 
 character(len=labellen) :: tfname
 character(len=labellen) :: int_name
 integer :: ifname
 logical :: lexists
 ifname=0
 tfname=fname 
 do while(ifname.lt.nfname)
    write(*,*) 'Checking if: ',trim(fname),' exists ...'
    lexists= file_exists(fname) 
    if( lexists) then
      write(*,*) 'It does....'
      write(int_name,'(".",I4.4)')(ifname)
      fname=trim(tfname)//trim(int_name)
      ifname=ifname+1
    else
      write(*,*) 'It does NOT, I shall open it'
      ifname=nfname
    endif
 enddo
 if (lexists) then
   write(*,*) 'cannot open file to write after', nfname,'attempsts'
   call fatal_error('sorry','crashing') 
 endif
endsubroutine reiterate_file
!%-----------------------------------------------
!
end module mod_read_write
